<template>
  <el-dialog
    v-model="visible"
    :title="`学员详情 - ${studentData.studentName}`"
    width="80%"
    top="5vh"
    fullscreen
    class="student-detail-dialog"
  >
    <el-tabs v-model="activeTab">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学员ID">TS10000{{ studentData.id }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ studentData.studentName }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ GENDER_OPTIONS.find(item => item.value === studentData.gender)?.label || '' }}
          </el-descriptions-item>
          <el-descriptions-item label="年龄">{{ studentData.age }}</el-descriptions-item>
          <el-descriptions-item label="联系方式"><span v-permission="['editStudent']">{{ studentData.phone }}</span></el-descriptions-item>
          <el-descriptions-item label="学员来源">
            {{ SOURCE_OPTIONS.find(item => item.value === studentData.source)?.label || '' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="STATUS_TAG_TYPE[studentData.status]">
              {{ STATUS_OPTIONS.find(item => item.value === studentData.status)?.label || '' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="入学时间">{{ parseISODateTime(studentData.enrollDate, {includeTime: false})  }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ studentData.remark || '无' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 学习进度 -->
        <div class="progress-section" v-for="item in courseList">
          <h4>{{ item.courseName }}</h4>
          <el-progress 
            :percentage="(progressPercentage(item.finishedLessons, item.totalLessons))" 
            status="success" 
          />
          <div class="progress-stats">
            <el-statistic title="已上课时" :value="item.finishedLessons" />
            <el-statistic title="剩余课时" :value="item.totalLessons - item.finishedLessons" />
            <el-statistic title="完成率" :formatter="() => progressPercentage(item.finishedLessons, item.totalLessons) + '%'" />
          </div>
        </div>
      </el-tab-pane>

      <!-- 课程记录 -->
      <el-tab-pane label="课程记录" name="courses">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="日期">
            <el-date-picker
              v-model="searchForm.date"
              type="daterange"
              placeholder="选择日期"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 300px;"
              value-format="YYYY-MM-DDTHH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="上课状态">
            <el-select style="width: 150px;" v-model="searchForm.crType" placeholder="请选择上课状态">
              <el-option label="正常上课" value="1" />
              <el-option label="迟到" value="2" />
              <el-option label="旷课" value="3" />
              <el-option label="请假" value="4" />
              <el-option label="早退" value="5" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getCourseRecords">查询</el-button>
            <el-button type="default" @click="resetSearchForm">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="courseRecords" style="width: 100%">
          <el-table-column prop="courseName" label="课程名称" />
          <el-table-column prop="schoolTime" label="日期" width="220" sortable />
          <el-table-column prop="teacherName" label="教师" width="150" />
          <el-table-column prop="crType" width="150" label="上课状态">
            <template #default="{ row }">
              {{ row.crType === '1' ? '正常上课' : row.crType === '2' ? '迟到' : row.crType === '3' ? '旷课' : row.crType === '4' ? '请假' : '早退' }}
            </template>
          </el-table-column>
          <el-table-column prop="content" label="课程内容" />
          <el-table-column prop="job" label="作业" />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{row}">
              <el-button :link="true" type="danger" @click="delRourseRecord(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          style="margin-top: 20px;" 
          :current-page="searchForm.page"
          :page-size="searchForm.pageSize"
          :page-sizes="[5, 10, 20, 30]"
          :total="searchForm.total" 
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-tab-pane>

      <!-- 跟进记录 -->
      <el-tab-pane label="跟进记录" name="follow">
        <div class="follow-header">
          <h4>跟进历史</h4>
          <el-button type="primary" size="small" @click="showAddFollowDialog">
            <el-icon><Plus /></el-icon>新增记录
          </el-button>
        </div>
        <el-timeline>
          <el-timeline-item
            v-for="(record, index) in followRecords"
            :key="index"
            :timestamp="record.updateTime"
            placement="top"
          >
            <el-card>
              <div class="record-header">
                <span class="record-type">
                  {{ STATUS_OPTIONS.find(item => item.value === record.nowStatus)?.label || '' }}
                </span>
                <span class="record-staff">{{ record.systemUserName }}</span>
                <el-button 
                  type="primary"
                  link
                  size="small" 
                  @click="editFollowRecord(record)"
                  style="margin-left: auto;"
                >
                  编辑
                </el-button>
              </div>
              <div class="record-content">{{ record.content }}</div>
              <div class="record-images" v-if="record.urls && record.urls.length > 0">
                <el-image
                  v-for="(url, i) in record.urls"
                  :key="i"
                  :src="url"
                  :preview-src-list="record.urls"
                  fit="cover"
                  style="width: 80px; height: 80px; margin-right: 10px;"
                />
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-tab-pane>
    </el-tabs>

    <!-- 新增跟进记录对话框 -->
    <el-dialog
      v-model="followDialogVisible"
      :title="`${followEditMode === 'add' ? '新增' : '编辑'}跟进记录`"
      width="50%"
    >
      <el-form :model="followForm" :rules="followRules" ref="followFormRef">
        <el-form-item label="跟进内容" prop="content">
          <el-input
            v-model="followForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入跟进内容"
          />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            v-model:file-list="followForm.images"
            action="/api/upload"
            :headers="{ 'Authorization': `Bearer ${getToken()}` }"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="followDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFollowRecord">确认</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { parseISODateTime } from '@/utils/dateUtils'
import {getCourseRecordsByStudentId, deleteCourseRecord} from '@/api/courseRecord'
import { getToken } from '@/utils/auth'
import { getFollowRecords, insertFollowRecord, updateFollowRecord } from '@/api/studentFollowRecord'
import { getCourseListByStudentId } from '@/api/course'
import { 
  GENDER_OPTIONS,
  SOURCE_OPTIONS,
  STATUS_OPTIONS,
  STATUS_TAG_TYPE
} from '@/constants/student'
import {useSystemStore} from '@/stores/system'
const systemStore = useSystemStore()

const props = defineProps({
  modelValue: Boolean,
  studentData: Object
})

const emit = defineEmits(['update:modelValue', 'refresh'])

const visible = ref(false)
const activeTab = ref('basic')
const followDialogVisible = ref(false)
const followEditMode = ref('add') // 'add' or 'edit'
const currentFollowId = ref('')
const courseList = ref([])

const searchForm = reactive({
  date: [],
  crType: '',
  total: 0,
  page: 1,
  pageSize: 5
})

const getCourseRecords = () => {
  console.log(searchForm.date)
  getCourseRecordsByStudentId({
    studentId: studentData.id,
    start: searchForm.date && searchForm.date.length > 0 ? searchForm.date[0] : null,
    end: searchForm.date && searchForm.date.length > 0 ? searchForm.date[1].replace('00:00:00', '23:59:59') : null,
    crType: searchForm.crType,
    page: searchForm.page,
    pageSize: searchForm.pageSize

  }).then(res => {
    courseRecords.value = res.data.list
    searchForm.total = res.data.total
  })
}

const resetSearchForm = () => {
  searchForm.date = []
  searchForm.crType = ''
  searchForm.total = 0
  searchForm.page = 1
  searchForm.pageSize = 5
  getCourseRecords()
}

const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  searchForm.page = 1
  searchForm.pageSize = val
  getCourseRecords()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  searchForm.page = val
  getCourseRecords()
}


// 学员数据
const studentData = reactive({
  id: '',
  studentName: '',
  gender: '1',
  age: 10,
  phone: '',
  source: '1',
  status: '3',
  birthday: '',
  birthdayType: '1',
  enrollDate: '',
  remark: ''
})

const progressPercentage  = (attended, total) => {
  return Math.round((attended / total) * 100)
}

// 课程记录
const courseRecords = ref([])

// 跟进记录
const followRecords = ref([])

// 跟进表单
const followForm = reactive({
  content: '',
  images: []
})

const followRules = {
  type: [{ required: true, message: '请选择跟进类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入跟进内容', trigger: 'blur' }]
}

const followFormRef = ref(null)

// 监听显示状态
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    loadStudentData()
    getCourseRecords()
    getFollowRecords(studentData.id).then(res => {
      followRecords.value = res.data.map(el =>{
      if (el.images.indexOf(',') == -1){
        return el
      }
      return {
        ...el,
        urls: el.images.split(',')[0] == '' ? [] : el.images.split(','),
        images: el.images.split(',')[0] == '' ? [] : el.images.split(',').map(url => {
          return {
            name: url.split('/').pop(), // 从URL提取文件名
            url,
            response:{
              data: url
            },
            status: 'success'
          }
        })
      }
    })
    })
    getCourseListByStudentId(studentData.id).then(res => {
      courseList.value = res.data
    })
  } else {
    searchForm.date = []
    searchForm.crType = ''
    searchForm.total = 0
    searchForm.page = 1
    searchForm.pageSize = 5
    activeTab.value = 'basic'
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 从props加载学员数据
const loadStudentData = () => {
  if (props.studentData) {
    Object.keys(props.studentData).forEach(key => {
      if (key in studentData) {
        studentData[key] = props.studentData[key]
      }
    })
  }
}

// 显示新增跟进记录对话框
const showAddFollowDialog = () => {
  followEditMode.value = 'add'
  resetFollowForm()
  followDialogVisible.value = true
}

// 编辑跟进记录
const editFollowRecord = (record) => {
  followEditMode.value = 'edit'
  currentFollowId.value = record.id
  Object.assign(followForm, {
    content: record.content,
    images: record.images || []
  })
  followDialogVisible.value = true
}

// 重置跟进表单
const resetFollowForm = () => {
  followForm.content = ''
  followForm.images = []
}

// 提交跟进记录
const submitFollowRecord = async () => {
  try {
    await followFormRef.value.validate()
    
    const recordData = {
      nowStatus: studentData.status,
      systemUserId: systemStore.getUserInfo.id,
      studentId: studentData.id,
      content: followForm.content,
      images: followForm.images.map(img => img.response.data).join(',')
    }
    
    if (followEditMode.value === 'add') {
      await insertFollowRecord(recordData)
    } else {
      recordData.id = currentFollowId.value
      await updateFollowRecord(recordData)
    }
    
    ElMessage.success(`${followEditMode.value === 'add' ? '新增' : '更新'}成功`)
    followDialogVisible.value = false
    // 刷新跟进记录列表
    const res = await getFollowRecords(studentData.id)
    followRecords.value = res.data.map(el =>{
      return {
        ...el,
        urls: el.images.split(',')[0] == '' ? [] : el.images.split(','),
        images: el.images.split(',')[0] == '' ? [] : el.images.split(',').map(url => {
          return {
            name: url.split('/').pop(), // 从URL提取文件名
            url,
            response:{
              data: url
            },
            status: 'success'
          }
        })
      }
    })
    emit('refresh')
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.includes('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
  }

  return isImage && isLt2M
}

const delRourseRecord = async (row) => {
  try {
    await deleteCourseRecord(row)
    ElMessage.success('删除成功')
    getCourseRecords()
  } catch (error) {
    console.error('删除失败', error)
    ElMessage.error('删除失败')
  }
}
</script>

<style scoped>
.student-detail-dialog {
  max-height: 80vh;
  overflow-y: auto;
}

.progress-section {
  margin-top: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.progress-section h4 {
  margin-bottom: 15px;
  color: #606266;
}

.progress-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

.follow-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.record-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.record-type {
  font-weight: bold;
  margin-right: 10px;
}

.record-staff {
  color: #909399;
  font-size: 14px;
}

.record-content {
  line-height: 1.6;
  margin-bottom: 10px;
}

.record-images {
  margin-top: 10px;
}
</style>
